$(function () {
    $.ajax({
        url: "http://120.27.209.174:1010/api/v1/posts_type",
        success(res) {
            res.forEach(function(item) {
                $(`<option value="${item.type}">${item.text}</option>`).appendTo("#type")
            })
        }
    })
    //富文本编辑器
    const E = window.wangEditor
    const editor = new E("#div1")
    editor.config.height = 220
    editor.config.uploadImgShowBase64 = true
    editor.create()
    //表单验证
    $(".needs-validation").validate({
        //debug: true, //调试模式取消submit的默认提交功能
        //errorClass: "label.error", //默认为错误的样式类为：error
        focusInvalid: false, //当为false时，验证无效时，没有焦点响应
        onkeyup: false,
        submitHandler: function(form){   //表单提交句柄,为一回调函数，带一个参数：form
            // 序列化之后的数据
            const data = serializeObject(form)
            data.detail = editor.txt.html()
            $.ajax({
                method: "POST",
                url: "http://120.27.209.174:1010/api/v1/posts",
                data: data,
                success(res) {
                    location.href = "./posts.html"
                },
                error(err) {
                    alert("发布失败，标题不能重复，或者其他原因，请刷新重试")
                }
            })
        },
        rules:{
            title: {required:true, rangelength:[ 10, 30]},
            description: {required:true},
            poster: {required:true, url: true},
            author: {required:true},
            type: {required:true},
            detail: {required:true},
        },
        messages:{
            type:"必选"
        }
    })
    function serializeObject(form) {
        let o = {};
        let a = $(form).serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    }
})